package com.eleventwelve.iris.web.validator;

import java.io.IOException;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

import com.eleventwelve.iris.entity.PhotoUploadable;
import com.eleventwelve.iris.utilities.ImageUtil;

public class ImageValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return PhotoUploadable.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object obj, Errors err) {

		PhotoUploadable photoUploadable = (PhotoUploadable) obj;

		MultipartFile multipartFile = photoUploadable.getPhoto();

		if (multipartFile != null && !multipartFile.isEmpty()) {
			
			String contentType = multipartFile.getContentType().substring(0, 6);

			if (!"image/".equals(contentType)) {

				err.rejectValue("photo",
						"error.account-settings.invalid-file-format",
						"Invalid file. Profile Image must be in PNG, JPEG, GIF or BMP format.");

			} else {

				if (multipartFile.getSize() < 1024 * 1024 * 10) {

					try {
						if (!ImageUtil.isValidSize(multipartFile
								.getInputStream())) {
							err.rejectValue(
									"photo",
									"error.account-settings.invalid-image-size",
									"Profile Image must be at least 250 x 250 pixels in size.");
						}
					} catch (IOException e) {

					}

				} else {

					err.rejectValue("photo",
							"error.account-settings.invalid-file-size",
							"Invalid file. Maximum file size is 10 Megabytes");

				}

			}
		}

	}

}
